<?php
global $CITYID;
error_reporting(E_ERROR | E_WARNING | E_PARSE);
mb_internal_encoding("UTF-8");
date_default_timezone_set("Asia/Chongqing");
chdir("/data/www/w.mdeve.com/htdocs/");

require 'runtime.php';

$data = get_file("http://www.cnpm25.cn/");
$data = skip_to_str($data, "getcurrcity();");
$data = get_front_str($data, "</div>");
$city = array();
for(;;){
	if(!strpos($data, "<a href=\"")) break;
	$data = skip_to_str($data, "<a href=\"");
	$url = get_front_str($data, "\"");
	$py = substr($url, 5, strpos($url, ".")-5);
	$data = skip_to_str($data, "<strong>");
	$cityname = clear_html(get_front_str($data, "</strong>"));
	$city[] = array("url"=>$url, "py"=>$py, "city"=>$cityname);
}

require 'library/defined.cityid.php';
foreach ($city as $k=>$v){
	if(array_key_exists($v["py"], $CITYID)){
		$city[$k]["cityid"] = $CITYID[$v["py"]];
	}
}

// 清理没有城市ID的
foreach ($city as $k=>$v){
	if(!array_key_exists("cityid", $v)) unset($city[$k]);
}

// 写入到数据库
$db = init_db();
$db->startTrans();
try{
	
	foreach ($city as $k=>$v){
		$row = $db->get_row("select count(*) as num from weather_aqi where cityid=$v[cityid]");
		if(!$row["num"]){		// 没有记录，新建
			$db->execute("insert into weather_aqi(cityid,city,url) values($v[cityid],'$v[city]','$v[url]')");
		}else{						// 有记录，更新
			$db->execute("update weather_aqi set city='$v[city]',url='$v[url]' where cityid=$v[cityid]");
		}
	}
	
	$db->commit();
}catch (Exception $e){
	$db->rollback();
}

echo "done";







?>